package net.babelphish.altitudesig.SigElements;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;

import com.google.appengine.api.images.Image;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.DataUtil;
import com.googlecode.charts4j.Fills;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Line;
import com.googlecode.charts4j.LineChart;
import com.googlecode.charts4j.Plots;

public class RatingChartSigElement extends SigElement {
	
	RatingChartSigElement() {
	}
	
	final static int maximumRatings = 46;	
		
	private URL generateChartURL(ArrayList<Double> ratings)
	{
		//cull ratings list
		if (ratings.size() > maximumRatings) { //we want to reduce the number of ratings so it isn't so jagged
			ArrayList<Double> newRatingsSet = new ArrayList<Double>();
			double ratio = ((ratings.size()) / (double)maximumRatings);
			
			newRatingsSet.add(ratings.get(0));
			for(int i = 0; i < maximumRatings; i++) {
				Integer sparseRatingIndex = (int) (ratio * i); 
				if ((sparseRatingIndex > 0) && (sparseRatingIndex < (ratings.size() - 1)))
				{
					newRatingsSet.add(ratings.get(sparseRatingIndex));
				}
			}
			newRatingsSet.add(ratings.get(ratings.size() - 1));
			
			ratings = newRatingsSet;
		}
		Double smallestRating = Collections.min(ratings);
		Double largestRating = Collections.max(ratings);
		Data ratingsData = DataUtil.scaleWithinRange(smallestRating - 50, largestRating + 50, ratings);
		double[] scaledData = ratingsData.getData();
		double rangeLine = scaledData[0];
        Line line1 = Plots.newLine(Data.newData(scaledData), Color.WHITE);
        // Defining chart.
        
        LineChart chart = GCharts.newLineChart(line1);
        chart.addHorizontalRangeMarker(rangeLine-1, rangeLine + 1, Color.ORANGE);        
        chart.setSize(150, 40);
        chart.setBackgroundFill(Fills.newSolidFill(Color.newColor("000000", 100)));
        
        // Fetch the image at the location given by the url query string parameter
		URL url = null;
		try {
			url = new URL(chart.toURLString());
			URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef());
			url = uri.toURL();
			
		} catch (MalformedURLException e) {
		} catch (URISyntaxException e) {
		}
		return url;
	}

	@Override
	public Image drawSelf(Object context) {
		// TODO Auto-generated method stub
		return null;
	}

}
